package main

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"github.com/tjfoc/gmsm/x509"
)

func Sign(msg []byte, sks []byte) (string, error) {

	sk, err := x509.ReadPrivateKeyFromPem(sks, nil)
	if err != nil {
		return "", err
	}

	h := sha256.Sum256(msg)
	sign, err := sk.Sign(rand.Reader, h[:], nil)
	if err != nil {
		return "", nil
	}

	return base64.StdEncoding.EncodeToString(sign), nil
}

func Verify(msg, signstr, pubKey []byte) (bool, error) {
	var err error

	pk, err := x509.ReadPublicKeyFromPem(pubKey)
	if err != nil {
		return false, err
	}

	//对待签名内容进行hash运算
	h := sha256.Sum256(msg)
	sign, _ := base64.StdEncoding.DecodeString(string(signstr))
	res := pk.Verify(h[:], sign)

	return res, nil
}
